package site.jlopen.controller.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import site.jlopen.assets.config.ThreadAuthUser;
import site.jlopen.domain.data.event.KusciaDataEvent;
import site.jlopen.domain.node.event.KusciaNodeEvent;
import site.jlopen.domain.project.KusciaProject;
import site.jlopen.domain.project.KusciaProjectInvite;
import site.jlopen.domain.project.KusciaProjectRead;
import site.jlopen.domain.project.event.KusciaProjectEvent;
import site.jlopen.domain.project.event.KusciaProjectInviteEvent;
import site.jlopen.entity.BaseResponse;
import site.jlopen.mapper.data.KusciaDataMapper;
import site.jlopen.mapper.node.KusciaNodeMapper;
import site.jlopen.mapper.project.KusciaProjectFlowMapper;
import site.jlopen.mapper.project.KusciaProjectInviteMapper;
import site.jlopen.mapper.project.KusciaProjectMapper;
import site.jlopen.mapper.project.KusciaProjectReadMapper;
import site.jlopen.secret.model.project.SecretProjectCreateReq;
import site.jlopen.service.intf.data.DataService;
import site.jlopen.service.intf.project.ProjectService;
import site.jlopen.utils.id.IdUtils;

@RestController
@RequestMapping(value="/api/project")
public class ApiProjectController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private ProjectService projectService;
	@Autowired
	private KusciaProjectMapper projectMapper;
	@Autowired
	private KusciaNodeMapper nodeMapper;
	@Autowired
	private KusciaProjectInviteMapper inviteMapper;
	@Autowired
	private KusciaDataMapper dataMapper;
	@Autowired
	private KusciaProjectReadMapper readMapper;
	@Autowired
	private DataService dataService;
	@Autowired
	private KusciaProjectFlowMapper flowMapper;
	
	@PostMapping(value = "/create" )
	public BaseResponse<String> create(@RequestBody SecretProjectCreateReq form) {
		logger.info("创建项目");
		KusciaNodeEvent nEvent = nodeMapper.selectByKey(form.getInitiatorNodeId());
		if(null == nEvent) {
			return new BaseResponse<String>().error("发起节点不存在");
		}
		KusciaProject pEvent = projectMapper.selectByInfo(new KusciaProjectEvent().setProjectUserId(ThreadAuthUser.id()).setProjectName("API-" + form.getCode()));
		if(null != pEvent) {
			return new BaseResponse<String>().error("项目编号"+form.getCode()+"已存在");
		}
		pEvent = new KusciaProject();
		pEvent.setProjectUserId(ThreadAuthUser.id())
		.setProjectId(IdUtils.SnowFlakeId())
		.setProjectName("API-" + form.getCode())
		.setProjectDesc("API调用创建" + form.getDesc())
		.setProjectModel(form.getModel())
		.setProjectChannel(form.getType())
		.setProjectFinish(0)
		.setProjectNodeId(nEvent.getNodeId())
		.setProjectStatus(0)
		.setProjectCreate(new Date())
		;
		int row = projectMapper.insertSelective(pEvent);
		if(row > 0) {
			/*KusciaProjectInvite invite = new KusciaProjectInvite()
			.setInviteId(IdUtils.SnowFlakeId())
			.setInviteProjectId(pEvent.getProjectId())
			.setInviteNodeId(nEvent.getNodeId())
			.setInviteStatus(1)
			.setInviteRole("owner")
			.setInviteCreate(new Date());
			inviteMapper.insert(invite);*/
			projectService.saveFlow(pEvent.getProjectId(), "默认训练流");
		}
		return new BaseResponse<String>().dbRes(row, "创建成功");
	}
	
	@PostMapping(value = "/finish" )
	public BaseResponse<String> finish(String projectCode) {
		logger.info("归档项目");
		KusciaProject pEvent = projectMapper.selectByInfo(new KusciaProjectEvent().setProjectUserId(ThreadAuthUser.id()).setProjectName("API-" + projectCode));
		if(null == pEvent) {
			return new BaseResponse<String>().error("项目编号"+projectCode+"不存在");
		}
		pEvent.setProjectFinish(1);
		pEvent.setProjectFinishTime(new Date());
		int row = projectMapper.updateSelective(pEvent);
		return new BaseResponse<String>().dbRes(row, "归档成功");
	}
	
	@PostMapping(value = "/invite" )
	public BaseResponse<String> invite(String projectCode, Long nodeId, Long dataId) {
		logger.info("添加项目合作方");
		KusciaProject pEvent = projectMapper.selectByInfo(new KusciaProjectEvent().setProjectUserId(ThreadAuthUser.id()).setProjectName("API-" + projectCode));
		if(null == pEvent) {
			return new BaseResponse<String>().error("项目编号"+projectCode+"不存在");
		}
		KusciaNodeEvent nEvent = nodeMapper.selectByKey(nodeId);
		if(null == nEvent) {
			return new BaseResponse<String>().error("合作节点不存在");
		}
		KusciaDataEvent dEvent = dataMapper.selectByKey(dataId);
		if(null == dEvent) {
			return new BaseResponse<String>().error("合作节点数据"+dataId+"不存在");
		}
		KusciaProjectInvite invite = new KusciaProjectInvite()
				.setInviteId(IdUtils.SnowFlakeId())
				.setInviteProjectId(pEvent.getProjectId())
				.setInviteNodeId(nEvent.getNodeId())
				.setInviteStatus(1)
				.setInviteRole(pEvent.getProjectNodeId().compareTo(nodeId) == 0? "owner" :  "partner")
				.setInviteCreate(new Date());
		int row = inviteMapper.insert(invite);
		if(row > 0) {
			KusciaProjectRead readEvent = new KusciaProjectRead();
			readEvent.setReadId(IdUtils.SnowFlakeId());
			readEvent.setReadDataId(dataId);
			readEvent.setReadInviteId(invite.getInviteId());
			readEvent.setReadCreate(new Date());
			int rrow = readMapper.insertSelective(readEvent);
			if(rrow > 0) {
				Map<String, Object> record = new HashMap<String, Object>();
				record.put("inviteProjectId", pEvent.getProjectId());
				List<KusciaProjectInviteEvent>  invites = inviteMapper.selectAllNotPage(record);
				if(null != invites && invites.size() > 0) {
					Long flowId = flowMapper.selectDefFlow(pEvent.getProjectId());
					for (KusciaProjectInviteEvent iinvite : invites) {
						for (KusciaProjectInviteEvent inviteTarget : invites) {
							if(iinvite.getInviteNodeId().compareTo(inviteTarget.getInviteNodeId()) != 0) {
								KusciaProjectRead readData = readMapper.selectByInfo(new KusciaProjectRead()
										.setReadInviteId(iinvite.getInviteId()));
								if(null != readData) {
									dataService.refreshDataGrant(flowId, iinvite.getInviteNodeId(), readData.getReadDataId(), inviteTarget.getInviteNodeId());
								}
							}
						}
					}
				}
			}
		}
		return new BaseResponse<String>().dbRes(row, "添加成功");
	}
	
	
}